package com.bridgeintelligent.tag.customer.service;

import com.alibaba.fastjson.JSON;
import com.bridgeintelligent.tag.customer.mapper.*;
import com.bridgeintelligent.tag.customer.pojo.*;
import com.bridgeintelligent.tag.utils.FieldHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 静态客群服务层接口实现
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
@Slf4j
public class StaticCustomersServiceImpl implements StaticCustomersService {

    private StaticCustomersMapper mapper;
    private CustomersMapper customersMapper;
    private QueryModelMapper queryModelMapper;

    /**
     * 获取静态客群的筛选条件信息(组装为动态格式返回)
     *
     * @param customersId
     * @return
     */
    @Override
    public Customers findStaticFilters(String customersId) {
        //客群信息
        Customers customers = customersMapper.findOneById(customersId);
        if (customers == null){
            return new Customers();
        }
        //客群查询条件
        QueryModel queryModel = queryModelMapper.findOneQueryModel(customers.getCustomersId());
        setEsTime(queryModel,customers.getIndexId());
        queryModel.setFields(JSON.parseArray(queryModel.getDimIds(), String.class));
        queryModel.setFieldTimeType(false);
        if (queryModel.getFields() != null && !queryModel.getFields().isEmpty()) {
            String dimName = "";
            Map<String, String> dimMsg = new HashMap<>();
            for (String field : queryModel.getFields()) {
                //查出输出标签名
                dimName = queryModelMapper.findDimNameById(field);
                dimMsg.put(field, dimName);
            }
            queryModel.setDimMsg(dimMsg);
        }
        //查询filter列表
        List<Filter> filters = new ArrayList<>();
        List<FilterGroup> filterGroups = findFilterGroup("-", customersId, filters);
        queryModel.setFilterGroup(filterGroups.get(0));
        customers.setQueryModel(queryModel);
        //查询列表
        if (!filters.isEmpty()) {
            Map<String, String> filtermap;
            for (Filter filter : filters) {
                filtermap = new HashMap<>();
                if (filter.getValueList() != null && !filter.getValueList()
                        .isEmpty()) {
                    String valueName = "";
                    for (String value : filter.getValueList()) {
                        Map<String, String> map = new HashMap<>();
                        map.put("dim_id", filter.getDimId());
                        map.put("item_no", value);
                        valueName = queryModelMapper.findValueName(map);
                        filtermap.put(value, valueName);
                    }
                }
                filter.setValueName(filtermap);
            }
            customers.setFilterList(filters);
        }
        return customers;
    }

    //动静态分开处理 动态：
    private void setEsTime(QueryModel queryModel,String indexId) {
        //这里主要处理详情回显客群的8位数据日期
        if (FieldHandler.pattern.matcher(queryModel.getFieldsDataDate()).matches() && queryModel.getFieldsDataDate().length() == FieldHandler.LENGTH8){
            String esTime = queryModelMapper.esRealTime(indexId);
            if (StringUtils.isNotEmpty(esTime)){
                queryModel.setFieldsDataDate(esTime);
            }
        }else{
            queryModel.setFieldsDataDate(mapper.findSymbol(indexId,queryModel.getFieldsDataDate()));
        }
    }


    //查询条件组
    public List<FilterGroup> findFilterGroup(String parentId, String customersId, List<Filter> filters) {
        Map<String, String> fgmap = new HashMap<>();
        fgmap.put("parentId", parentId);
        fgmap.put("customers_id", customersId);
        List<FilterGroup> filterGroupList = queryModelMapper.findFilterGroup(fgmap);
        Filter filter;
        List<Filter> filterList;
        if (filterGroupList != null && !filterGroupList.isEmpty()) {
            for (FilterGroup filterGroup : filterGroupList) {
                filterList = new ArrayList<>();
                //查找条件
                List<String> filterIds = queryModelMapper.findFilterIds(filterGroup.getId());
                if (filterIds != null && !filterIds.isEmpty()) {
                    for (String filterId : filterIds) {
                        filter = queryModelMapper.findOneFilterById(filterId);
                        filter.setValueList(JSON.parseArray(filter.getValueListStr(), String.class));
                        filter.setTimeType(false);
                        filter.setDataDate(fetchStaticDate(filter.getIndexId(),filter.getDataDate()));
                        filterList.add(filter);
                        filters.add(filter);
                    }
                }
                filterGroup.setFilters(filterList);
                filterGroup.setTimeType(false);
                List<FilterGroup> list = findFilterGroup(filterGroup.getId(), customersId, filters);
                if (list != null && !list.isEmpty()) {
                    filterGroup.setChildren(list);
                }else{
                    filterGroup.setChildren(new ArrayList<FilterGroup>());
                }
            }
        }
        return filterGroupList;
    }

    private String fetchStaticDate(String indexId,String dataDate){
        if (FieldHandler.ZERO.equals(dataDate) || (FieldHandler.pattern.matcher(dataDate)).matches() && dataDate.length() == FieldHandler.LENGTH8) {
            return FieldHandler.ZERO;
        }
        return mapper.findSymbol(indexId,dataDate);
    }

}
